package com.song.week.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.song.week.domain.TestUser;
import com.song.week.dto.LoginDto;
import com.song.week.service.TestUserService;
import com.song.week.mapper.TestUserMapper;
import com.song.week.utils.AppJwtUtil;
import com.song.week.utils.R;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

/**
* @author Administrator
* @description 针对表【test_user】的数据库操作Service实现
* @createDate 2024-06-11 16:22:39
*/
@Service
public class TestUserServiceImpl extends ServiceImpl<TestUserMapper, TestUser>
    implements TestUserService{

    @Override
    public R login(LoginDto dto) {
        if(StringUtils.isBlank(dto.getUsername()) || StringUtils.isBlank(dto.getPassword())){
            return R.error(301,"账号或密码不能为空！");
        }
        LambdaQueryWrapper<TestUser> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(TestUser::getUsername,dto.getUsername());
        TestUser user = baseMapper.selectOne(wrapper);
        if(Objects.isNull(user)){
            return R.error(302,"用户不存在！");
        }

        String sale = user.getSale();
        String username=dto.getUsername();
        if(!DigestUtils.md5DigestAsHex((username+sale).getBytes()).equals(user.getPassword())){
            return R.error(303,"密码错误！");
        }

        String token= AppJwtUtil.getToken(user.getId().longValue());
        Map<String,Object> map = new HashMap<>();
        map.put("token",token);
        user.setSale("");
        user.setPassword("");
        map.put("user",user);
        return R.success(map);

    }
}




